#!/usr/bin/env python

from __future__ import with_statement
import xml.dom.minidom as DOM
import urllib2
import dbus
import re
import datetime
import sys

LAST_RUN_DATE_TIME_FILE = '/home/user/Event Feed/examples/RSS Feed/last_run.txt' # File to read/write serialized date/time when script was last run.
SCRIPT_FILE = '/home/user/Event\ Feed/examples/RSS\ Feed/get_rss_feed' # Path to the script.

def get_rss_feed(feed = 'http://talk.maemo.org/external.php?type=RSS2'):
	""" Retrieve the RSS feed (default is latest TMO threads) and post events to the Hildon Event Feed. """
	
	source_name = 'rss_feed_example' # Source of the events
	display_name = 'RSS Feed' # Source name displayed in the event feed UI
	icon = '/usr/share/icons/hicolor/64x64/hildon/general_rss.png' # Icon for the events in the UI
	action = 'dbus:system com.nokia.osso_browser /com/nokia/osso_browser/request com.nokia.osso_browser load_url' # This will be called when the user taps on an item in the event feed. In this example, the link is opened in the browser.
	refresh_action = 'exec python %s %s' % (SCRIPT_FILE, feed) # When this refresh action is added, the script will be called again (with same feed) when the 'Refresh' button is pressed in the event feed UI.
	
	bus = dbus.SessionBus()
	iface = dbus.Interface(bus.get_object('com.maemo.eventFeed', '/'), 'com.maemo.eventFeed') # Get the event feed dbus object
	iface.addRefreshAction(source_name, refresh_action) # Add the refresh action to the event feed.
	
	last_run = script_last_run() # Time when script was last run. Will be used to check against the date/time of each item in the feed.
	
	rss = urllib2.urlopen(feed).read()
	doc = DOM.parseString(rss)
	items = doc.getElementsByTagName('item')
		
	link = ''
	title = ''
	body = ''
	images = []
	footer = ''
	timestamp = ''
		
	for item in items:
		for node in item.childNodes:
			nodeName = node.nodeName
			
			if nodeName == 'link':
				link = node.firstChild.data
			elif nodeName == 'title':
				title = node.firstChild.data
			elif nodeName == 'description':
				body = node.firstChild.data
			elif nodeName == 'dc:creator':
				footer = node.firstChild.data
			elif nodeName == 'pubDate':
				timestamp = node.firstChild.data
			elif nodeName == 'content:encoded':
				images = get_images(node.firstChild.data)
		
		try:
			item_date_time = datetime.datetime.strptime(timestamp[0:timestamp.rfind(' ')], '%a, %d %b %Y %H:%M:%S')
		except:
			print 'Cannot parse item date/time. Using default'
			item_date_time = datetime.datetime.min
		
		if item_date_time > last_run:
			print iface.addEvent(source_name, display_name, icon, title, body, images, footer, timestamp, '%s %s' % (action, link)) # If item is new, add an event to the event feed and print the reply.
		
	set_script_last_run(datetime.datetime.now().strftime('%Y, %m, %d, %H, %M, %S'))
	
def script_last_run():
	""" Read serialized date/time from last_run.txt. """
	
	date_time_string = ''
	last_run = datetime.datetime.min
	
	try:
		with open(LAST_RUN_DATE_TIME_FILE, 'r') as file:
			date_time_string = file.read()
			file.close()
			
		if date_time_string != '':
			try:
				last_run = datetime.datetime.strptime(date_time_string, '%Y, %m, %d, %H, %M, %S')
			except:
				print 'Saved date/time in incorrect format. Using default'
				
	except IOError:
		print 'Cannot read date/time from file. Using default.'
					
	return last_run
	
def set_script_last_run(date_time_string):
	""" Serialize the date/time the script was last run to last_run.txt. """

	try:
		with open(LAST_RUN_DATE_TIME_FILE, 'w') as file:
			file.write(unicode(date_time_string))
			file.close()
	except IOError:
		print 'Cannot write date/time to file'
	
def get_images(content):
	""" Try to extract image links from the content:encoded node. """
	
	images = re.findall('http://[^\s]+jpg|http://[^\s]+png', content)
	
	if len(images) > 2:
		images = images[0:2]
	
	return images
	
if __name__ == '__main__':
	if len(sys.argv) > 1:
		sys.exit(get_rss_feed(sys.argv[1]))
	else:
		sys.exit(get_rss_feed())